package com.tg.appcommon.app;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.os.Build;
import android.os.Bundle;

import java.lang.ref.WeakReference;
import java.util.concurrent.ConcurrentHashMap;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.tange.base.toolkit.AppUtil;
import com.tg.appcommon.android.TGLog;

public class AppLifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
    private static final String TAG = AppLifecycleCallbacks.class.getSimpleName();
    @Nullable
    private static WeakReference<Activity> sCurrentActivity;

    public static int getActivityNumber() {
        return mActivityNumber;
    }

    private static int mActivityNumber = 0;

    @SuppressLint("UseSparseArrays")
    private static ConcurrentHashMap<Integer, WeakReference<Activity>> sActivities = new ConcurrentHashMap<>();

    private AppStatusObserver mAppStatusChgObserver = AppStatusObserver.getInstance();

    public void setActivityStartListener(ActivityStartListener activityStartListener) {
        mActivityStartListener = activityStartListener;
    }

    private ActivityStartListener mActivityStartListener;


    public ConcurrentHashMap<Integer, WeakReference<Activity>> activities() {
        return sActivities;
    }

    @Nullable
    public Activity getCurrentActivity() {
        return sCurrentActivity == null? null : sCurrentActivity.get();
    }

    public void finishAllActivity() {
        for (int i : sActivities.keySet()) {
            if (sActivities.get(i) != null && sActivities.get(i).get() != null) {
                Activity activity = sActivities.get(i).get();
                if (!AppUtil.isActivityFinishingOrDestroyed(activity)) {
                    activity.finish();
                }
            }
        }
        sActivities.clear();
    }

    public void finishActivity(String className) {
        for (int i : sActivities.keySet()) {
            if (sActivities.get(i) != null && sActivities.get(i).get() != null) {
                Activity activity = sActivities.get(i).get();
                if (activity.getClass().getSimpleName().equalsIgnoreCase(className)){
                    if (!AppUtil.isActivityFinishingOrDestroyed(activity)) {
                        activity.finish();
                    }
                    return;
                }

            }
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public Activity getActivity(String className){
        try {
            for (int i : sActivities.keySet()) {
                if (sActivities.get(i) != null && sActivities.get(i).get() != null) {
                    Activity activity = sActivities.get(i).get();
                    if (activity.getClass().getSimpleName().equalsIgnoreCase(className)) {
                        return activity;
                    }
                }
            }
        } catch (Throwable ex) {
            // ignore
        }
        return null;
    }

    public void printActivity(){
        for (int i : sActivities.keySet()) {
            if (sActivities.get(i) != null && sActivities.get(i).get() != null) {
                Activity activity = sActivities.get(i).get();
                TGLog.d("className = " + activity.getClass().getSimpleName());
            }
        }
        if (sCurrentActivity != null && sCurrentActivity.get() != null){
            TGLog.d("CurrentActivity className = " + sCurrentActivity.get().getClass().getSimpleName());
        }
    }

    //获取栈中最顶端的Activity
    public Activity getNoFinishActivity(){
        Activity activity = null;
        if (sCurrentActivity != null && sCurrentActivity.get() != null){
            activity =  sCurrentActivity.get();
            if (!AppUtil.isActivityFinishingOrDestroyed(activity)) {
                return activity;
            }
        }
        for (int i : sActivities.keySet()) {
            if (sActivities.get(i) != null && sActivities.get(i).get() != null) {
                Activity a = sActivities.get(i).get();
                if (!AppUtil.isActivityFinishingOrDestroyed(a)) {
                    activity = a;
                }
            }
        }
        return activity;
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        TGLog.i(TAG, "onActivityCreated:" + activity);
        WeakReference<Activity> wa = new WeakReference<>(activity);
        sActivities.put(activity.hashCode(), wa);
    }

    @Override
    public void onActivityStarted(Activity activity) {
        TGLog.i(TAG, "onActivityStarted:" + activity);
        mActivityNumber++;
        TGLog.d(TAG, "activityNumber = " + mActivityNumber);
        TGLog.d("onActivityStarted activity className = " + activity.getClass().getSimpleName());
        if (mActivityStartListener != null){
            mActivityStartListener.onActivityStart();
        }
    }

    @Override
    public void onActivityResumed(Activity activity) {
        TGLog.i(TAG, "onActivityResumed:" + activity);
        sCurrentActivity = new WeakReference<>(activity);
        mAppStatusChgObserver.onActivityLifecycleEvent(activity, mActivityNumber, AppStatusObserver.EVENT_ON_ACTIVITY_RESUMED);
    }

    @Override
    public void onActivityPaused(Activity activity) {
        TGLog.i(TAG, "onActivityPaused:" + activity);

    }

    @Override
    public void onActivityStopped(Activity activity) {
        TGLog.i(TAG, "onActivityStopped:" + activity);
        mActivityNumber--;
        TGLog.d(TAG, "activityNumber = " + mActivityNumber);
        if (mActivityNumber == 0) {
            // app回到后台
            TGLog.d(TAG, "app回到后台");
        }
        TGLog.d("onActivityStopped activity className = " + activity.getClass().getSimpleName());
        mAppStatusChgObserver.onActivityLifecycleEvent(activity, mActivityNumber, AppStatusObserver.EVENT_ON_ACTIVITY_STOPPED);
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        TGLog.i(TAG, "onActivityDestroyed:" + activity);
        sActivities.remove(activity.hashCode());
    }

    public interface ActivityStartListener {
        void onActivityStart();
    }
}